import { logBaseDir, logBaseDirPath, logDirPath } from '@/utils';
import ChainPromiseCall from '@rasir/chain-promise-call';
import { invoke } from '@tauri-apps/api';
import {
  readTextFile,
  removeFile,
  writeFile,
  createDir,
} from '@tauri-apps/api/fs';
import { join } from '@tauri-apps/api/path';

const chianPromiseCall = ChainPromiseCall.getInstance();
const dirPath = logDirPath;
const logBaseDirType = logBaseDir;

export function logger(logText: string, fileName: string) {
  chianPromiseCall.push({
    run: async () => {
      await mkdir();
      const filePath = await join(dirPath, fileName);
      const text = await readTextFile(filePath, {
        dir: logBaseDirType,
      }).catch(() => {});
      await writeFile(
        filePath,
        `${text === undefined ? '' : `${text}\n`}${logText}`,
        {
          dir: logBaseDirType,
        },
      )
        .catch((e) => {
          console.log(`writeFile error:${e}`);
        })
        .then(() => {});
    },
  });
}
// 删除日志
export async function initLogger(fileName: string) {
  chianPromiseCall.push({
    run: async () => {
      await mkdir();
      const filePath = await join(dirPath, fileName);
      await removeFile(filePath, { dir: logBaseDirType }).catch((e) => {
        console.log(`removeFile error:${e}`);
      });
    },
  });
}
// 创建目录
export async function mkdir() {
  const dirFullPath = await join(await logBaseDirPath(), dirPath);
  const isExist = await isFileExist(dirFullPath);
  if (isExist) return;
  await createDir(dirPath, { dir: logBaseDirType, recursive: true })
    .then((e) => {
      console.log(`mkdir succcess:${e}`);
    })
    .catch((e) => {
      console.log(`mkdir error:${e}`);
    });
}

export async function queryLogs(logFileName: string, rowNum: number) {
  await mkdir();
  const filePath = await join(dirPath, logFileName);
  const text = await readTextFile(filePath, {
    dir: logBaseDirType,
  }).catch(() => {});
  if (text) {
    const logList = text.split(/\n/g);
    return {
      logs: logList.slice(rowNum),
      rowNum: logList.length,
    };
  }
  return {
    logs: [],
    rowNum: 0,
  };
}

export async function isFileExist(filePath: string) {
  return await invoke('file_exists', {
    path: filePath,
  });
}

export async function readFile(filePath: string) {
  const isExist = await isFileExist(filePath);
  if (!isExist) throw new Error('文件不存在');
  return await invoke('file_read', {
    path: filePath,
  });
}

export async function getAllProDirs(filePath: string) {
  const isExist = await isFileExist(filePath);
  if (!isExist) throw new Error('目录不存在');
  return await invoke('get_all_pro_dir', {
    path: filePath,
  });
}

export async function pathJoin(path: string, fileName: string) {
  return await join(path, fileName);
}
